# ******************************************************************************
#  Copyright (c) 2021-2022. Kneron Inc. All rights reserved.                   *
# ******************************************************************************
from .LibLoaderBase import LibLoaderBase
from weakref import WeakValueDictionary
import os
import abc
import ctypes


class Singleton(type):
    _instances = WeakValueDictionary()

    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            instance = super(Singleton, cls).__call__(*args, **kwargs)
            cls._instances[cls] = instance
        return cls._instances[cls]


class WrapperBase(metaclass=Singleton):
    def __init__(self, lib_loader: LibLoaderBase):
        self._lib = None
        self._lib_loader = lib_loader
        self._load_libKSI()
        self._init_sdk_functions()

    def _load_libKSI(self):
        for share_lib in self._lib_loader.share_libs:
            if os.path.basename(share_lib) in self._lib_loader.kneron_libs:
                self._lib = ctypes.CDLL(share_lib)
            else:
                ctypes.CDLL(share_lib, mode=ctypes.RTLD_GLOBAL)

    @property
    def LIB(self):
        return self._lib

    @abc.abstractmethod
    def _init_sdk_functions(self):
        pass
